package com.its.filter;

import com.its.pojo.LoginUser;
import com.its.util.JJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
/**
 * JWT认证Token过滤器
 * 用于从请求中获取JWT Token并验证用户身份，并将用户认证信息设置到Spring Security的上下文中。
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public JwtAuthenticationTokenFilter(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 1. 从请求头中获取Authorization字段的token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            // 2. 若token为空或null，则继续到下一个过滤器
            filterChain.doFilter(request, response);
            return;
        }

        // 3. 解析token获取UUID
        String uuid;
        try {
            JJwtUtil.checkToken(token);
            uuid = JJwtUtil.getMemberIdByJwtToken(token);
        } catch (Exception e) {
            throw new RuntimeException("无效的Token");
        }

        // 4. 从Redis中获取UUID对应的用户信息
        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get(uuid);
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("用户未登录");
        }

        // 5. 创建认证token并将其设置到SecurityContextHolder中
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(authentication);

        // 6. 继续到下一个过滤器
        filterChain.doFilter(request, response);
    }
}
